<template>
  <!-- 质量报告模版配置2.0表单弹窗 -->
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="1000px"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="160"
      >
        <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
        <div v-if="!props.isReadonly">
          <el-row>
            <el-col :span="12">
              <el-form-item label="客户" prop="customerId">
                <el-select
                  v-model="formData.customerId"
                  placeholder="请选择客户"
                  @change="partnerChange"
                  clearable
                >
                  <el-option
                    v-for="item in customerList"
                    :key="`${item.id}`"
                    :label="`${item.partnerName}`"
                    :value="`${item.id}`"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品" prop="materialId">
                <el-select
                  v-model="formData.materialId"
                  placeholder="请选择产品"
                  clearable
                  @change="materialChange"
                  filterable
                >
                  <el-option
                    v-for="item in materialList"
                    :key="`${item.materialId}`"
                    :label="`${item.materialName}`"
                    :value="`${item.materialId}`"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="图号" prop="materialDrawingNo">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.materialDrawingNo"
                  placeholder="请输入图号"
                  disabled
                  clearable
                />
                <span v-else>{{ formData.materialDrawingNo }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报告类型" prop="reportCategory">
                <el-select
                  v-model="formData.reportCategory"
                  placeholder="请选择报告类别"
                  clearable
                  @change="reportCategoryChange"
                >
                  <el-option
                    v-for="item in useDictionary('QmsReportType')"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="模版名称" prop="templateName">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.templateName"
                  placeholder="请输入模版名称"
                  clearable
                />
                <span v-else>{{ formData.templateName }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="标准" prop="images">
                <div class="pl-[30px] pr-[30px]">
                  <CommonUploadFile
                    :key="formData.images"
                    :showText="false"
                    :isRead="props.isReadonly"
                    :files="formData.images"
                    :limit="1"
                    :multiple="false"
                    accept=".jpg,.png,.jpeg"
                    @update-files="updateFormFiles"
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <el-descriptions
          v-else
          title=""
          :column="2"
          size="large"
          border
          style="width: 100%"
        >
          <el-descriptions-item label="客户">
            {{ formData.customerName }}
          </el-descriptions-item>
          <el-descriptions-item label="产品">
            {{ formData.materialName }}
          </el-descriptions-item>
          <el-descriptions-item label="图号">
            {{ formData.materialDrawingNo }}
          </el-descriptions-item>
          <el-descriptions-item label="报告类型">
            {{ useDictionary("QmsReportType", formData.reportCategory) }}
          </el-descriptions-item>
          <el-descriptions-item label="模版名称">
            {{ formData.templateName }}
          </el-descriptions-item>
          <el-descriptions-item label="框架">
            {{ formData.reportName }}
            <el-button plain @click="handleTemplate"> 查看框架 </el-button>
          </el-descriptions-item>
          <el-descriptions-item label="标准">
            <div class="pl-[30px] pr-[30px]" v-if="formData.images.length > 0">
              <CommonUploadFile
                :key="formData.images"
                :showText="false"
                :isRead="props.isReadonly"
                :files="formData.images"
                :limit="1"
                :multiple="false"
                accept=".jpg,.png,.jpeg"
                @update-files="updateFormFiles"
              />
            </div>
            <span v-else>无</span>
          </el-descriptions-item>
        </el-descriptions>
        <h4 class="mb-[20px] mt-[20px]">详细数据</h4>
        <el-card shadow="never" class="table-container">
          <template #header v-if="!props.isReadonly">
            <el-button type="success" plain @click="handleAdd">
              <i-ep-plus />
              新增
            </el-button>
            <el-form-item prop="reportTemplateId" style="float: right">
              <el-select
                v-model="formData.reportTemplateId"
                placeholder="请选择框架"
                clearable
                filterable
              >
                <el-option
                  v-for="item in reportTemplateList"
                  :key="`${item.id}`"
                  :label="`${item.reportName}`"
                  :value="`${item.id}`"
                />
              </el-select>
              <el-button plain @click="handleTemplate"> 查看框架 </el-button>
            </el-form-item>
          </template>
          <div class="formTable">
            <el-table
              :data="formData.details"
              style="width: 100%"
              :key="Math.random"
              border
            >
              <el-table-column
                label="排序"
                prop="sort"
                min-width="50"
                align="center"
              />
              <el-table-column
                label="检验类型"
                props="checkTypeId"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    v-if="!props.isReadonly"
                    :prop="'details.' + $index + '.checkTypeId'"
                    :rules="rules.soncheckTypeId"
                    label-width="0"
                    style="width: 100%"
                  >
                    <el-select
                      v-model="row.checkTypeId"
                      placeholder="请选择检验类型"
                      clearable
                      style="width: 100%"
                      @change="checkTypeChange(row)"
                      filterable
                    >
                      <el-option
                        v-for="item in checkTypeList"
                        :key="`${item.id}`"
                        :label="`${item.checkTypeCode} - ${item.checkTypeName}`"
                        :value="`${item.id}`"
                      />
                    </el-select>
                  </el-form-item>
                  <span v-else
                    >{{ row.checkTypeCode }} - {{ row.checkTypeName }}</span
                  >
                </template>
              </el-table-column>
              <el-table-column
                label="检验项目"
                props="checkItemId"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    v-if="!props.isReadonly"
                    :prop="'details.' + $index + '.checkItemId'"
                    :rules="rules.soncheckItemId"
                    label-width="0"
                    style="width: 100%"
                  >
                    <el-select
                      v-model="row.checkItemId"
                      placeholder="请选择检验项目"
                      clearable
                      filterable
                      style="width: 100%"
                    >
                      <el-option
                        v-for="item in row.checkItemList"
                        :key="`${item.id}`"
                        :label="`${item.checkItemCode} - ${item.checkItemName}`"
                        :value="`${item.id}`"
                      />
                    </el-select>
                  </el-form-item>
                  <span v-else
                    >{{ row.checkItemCode }} - {{ row.checkItemName }}</span
                  >
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="200"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.details.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                  >
                    删除
                  </el-button>
                  <el-button
                    :disabled="
                      formData.details.length < 2 || scope.row.sort == 1
                    "
                    link
                    @click.stop="up(scope.$index)"
                  >
                    上移
                  </el-button>
                  <el-button
                    :disabled="
                      formData.details.length < 2 ||
                      scope.row.sort == formData.details.length
                    "
                    link
                    @click.stop="down(scope.$index)"
                  >
                    下移
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handlePreview">预览模版</el-button>
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定
          </el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { ref } from "vue";
import { useDictionary } from "@/utils/useTable"; // 引入
import { useRouter } from "vue-router";
import { useReportModelConfigStore } from "../../pinia/ReportModelConfigStore";

const router = useRouter();
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSQMSREPORTMODELCONFIGADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});
/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (newVal) {
      getCustomer();
      getCheckTypeList();
    }
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  version: "",
  templateName: "",
  customerId: "",
  customerName: "",
  materialBatch: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  materialDrawingNo: "",
  materialQuality: "",
  reportCategory: "",
  reportDate: "",
  deviceType: "",
  reportTemplateId: "",
  reportName: "",
  approveStatus: "",
  approveUserId: "",
  approveUserName: "",
  approveDate: "",
  images: [],
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  details: [
    {
      id: "",
      configId: "",
      sort: 1,
      checkTypeId: "",
      checkItemId: "",
      version: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      enabled: "",
      deleted: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  version: [],
  templateName: [
    { required: true, message: "请输入模板名称", trigger: "blur" },
    { min: 1, max: 200, message: "长度在 1 到 200 个字符", trigger: "blur" },
  ],
  customerId: [
    { required: true, message: "请选择客户", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  materialBatch: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  materialId: [
    { required: true, message: "请选择产品", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  materialCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  materialName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  materialDrawingNo: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  materialQuality: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  reportCategory: [
    { required: true, message: "请选择报告类别", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  reportDate: [],
  deviceType: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  reportTemplateId: [
    { required: true, message: "请选择报告模板", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  approveStatus: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  approveUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  approveUserName: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  approveDate: [],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  createTime: [],
  createdUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  createdUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lastUpdateTime: [],
  lastUpdatedUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  enabled: [],
  deleted: [],
  sonconfigId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonsort: [],
  soncheckTypeId: [
    { required: true, message: "请选择检验类型", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  soncheckItemId: [
    { required: true, message: "请选择检验项目", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonversion: [],
  sonremarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  soncreateTime: [],
  soncreatedUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  soncreatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonlastUpdateTime: [],
  sonlastUpdatedUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonlastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonenabled: [],
  sondeleted: [],
});

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  for (let i = index; i < formData.details.length; i++) {
    formData.details[i].sort = formData.details[i].sort - 1;
  }
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  configId: "",
  sort: 1,
  checkTypeId: "",
  checkItemId: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  sondata.sort = formData.details.length + 1;
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
      if (formData.customerId) {
        getMaterials(formData.customerId);
      }
      if (formData.reportCategory) {
        getReportTemplateList();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.version = "";
  formData.templateName = "";
  formData.customerId = "";
  formData.customerName = "";
  formData.materialBatch = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.materialDrawingNo = "";
  formData.materialQuality = "";
  formData.reportCategory = "";
  formData.reportDate = "";
  formData.deviceType = "";
  formData.reportTemplateId = "";
  formData.reportName = "";
  formData.approveStatus = "";
  formData.approveUserId = "";
  formData.approveUserName = "";
  formData.approveDate = "";
  formData.images = [];
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  materialList.value = [];
  reportTemplateList.value = [];
}

const loading = ref(false);

/** 质量报告模版配置2.0保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/qms/qmsreportmodelconfig/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/qms/qmsreportmodelconfig/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
  formData.details.forEach((item) => {
    checkTypeChange(item);
  });
}

const customerList = ref([]);
const getCustomer = async () => {
  const { data } = await request({
    url: "mdm/mdmpartner/getList",
    method: "get",
    data: {},
  });
  customerList.value = data;
};

const partnerChange = () => {
  formData.materialId = "";
  materialChange();
  if (formData.customerId) {
    getMaterials(formData.customerId);
    formData.customerName = customerList.value.find(
      (item) => item.id === formData.customerId
    )?.partnerName;
  } else {
    materialList.value = [];
  }
};

const materialList = ref([]);
const getMaterials = async (customerId) => {
  const { data } = await request({
    url: `mdm/partnerproduct/materialList/${customerId}`,
    method: "get",
    data: {},
  });
  materialList.value = data;
};

const materialChange = () => {
  const find = materialList.value.find(
    (item) => item.materialId === formData.materialId
  );
  formData.materialDrawingNo = find?.figureNumber;
  formData.materialCode = find?.materialCode;
  formData.materialName = find?.materialName;
};

const checkTypeList = ref([]);
const getCheckTypeList = async () => {
  const { data } = await request({
    url: `qms/qmschecktype/getList`,
    method: "post",
    data: {},
  });
  checkTypeList.value = data;
};

const checkTypeChange = async (row) => {
  const { data } = await request({
    url: `qms/qmscheckitem/getList`,
    method: "post",
    data: { effectCheckTypeId: row.checkTypeId },
  });
  row.checkItemList = data;
};

const reportCategoryChange = () => {
  if (formData.reportCategory) getReportTemplateList();
  else reportTemplateList.value = [];
};

const reportTemplateList = ref([]);
const getReportTemplateList = async () => {
  const { data } = await request({
    url: `qms/qmsreporttemplate/getList`,
    method: "post",
    data: { reportCategory: formData.reportCategory },
  });
  reportTemplateList.value = data;
};

// 图片处理
function updateFormFiles(val: []) {
  formData.images = val;
}

const up = (index: any) => {
  swapElementsWithSort(formData.details, index, index - 1);
};

const down = (index: any) => {
  swapElementsWithSort(formData.details, index, index + 1);
};

function swapElementsWithSort(arr, index1, index2) {
  // 交换元素位置
  [arr[index1], arr[index2]] = [arr[index2], arr[index1]];

  // 如果元素有sort属性，也交换sort值
  if (arr[index1].sort !== undefined && arr[index2].sort !== undefined) {
    [arr[index1].sort, arr[index2].sort] = [arr[index2].sort, arr[index1].sort];
  }

  return arr;
}

const handleTemplate = () => {
  if (!formData.reportTemplateId) {
    return ElMessage.warning(`请选择报告模版`);
  }
  // 将数据存入 store
  const store = useReportModelConfigStore();
  store.setPreviewData({ reportTemplateId: formData.reportTemplateId });

  const find = reportTemplateList.value.find(
    (item) => item.id === formData.reportTemplateId
  );
  const to = {
    path: find.templateRoute,
  };
  router.push(to);
};

const handlePreview = () => {
  if (!formData.reportTemplateId) {
    return ElMessage.warning(`请选择报告模版`);
  }
  // 将数据存入 store
  const store = useReportModelConfigStore();
  store.setPreviewData(JSON.parse(JSON.stringify(formData)));
  const find = reportTemplateList.value.find(
    (item) => item.id === formData.reportTemplateId
  );
  const to = {
    path: find.templateRoute,
  };
  router.push(to);
};
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}

.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}

:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}

:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}

:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
</style>
